const cloud = require('wx-server-sdk')
const rp = require('request-promise');
const request = require('request');
cloud.init({
    env:'water-puryn'   
});

function requestNotRedirect(url) {
  return new Promise((resolve, reject) => {
    var options = {
      uri: url,
      headers: {
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
      },
      followRedirect: false,
      resolveWithFullResponse: true,
    };
    request.get(options, function (error, response, body) {
      resolve(response)
    })
  })
}

async function getParam(url) {
  const res = await requestNotRedirect(url)
  var pattern = new RegExp("video\/(.*?)\/.*?mid=(.*?)&");
  if (pattern.test(res.body)) {
    item_id = RegExp.$1;
    mid = RegExp.$2;
    return {
      'item_id': item_id,
      'mid': mid
    }
  } else {
    return null
  }

}

async function getItemInfo(item_id, mid) {
  var url = `https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${item_id}`
  try {
    var options = {
      uri: url,
      headers: {
        'authority': 'www.iesdouyin.com',
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'content-type': 'application/x-www-form-urlencoded',
        'accept': '*/*',
        'referer': `https://www.iesdouyin.com/share/video/${item_id}/?region=CN&mid=${mid}&u_code=15b9142gf&titleType=title&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme`,
        'accept-language': 'zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7'
      }
    };
    var res = await rp(options)
    return JSON.parse(res);
  } catch (err) {
    console.log(err)
  }

}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
};

async function parse(res_json) {
  var playwm = res_json.item_list ? res_json['item_list'][0]['video']['play_addr']['url_list'][0] : null
  if (playwm) {
    var tested = false;
    var try_count = 0;
    var paly_address = playwm.replace('playwm', 'play')
    var cover = res_json['item_list'][0]['video']['origin_cover']['url_list'][0];
    for (var i = 1; i < 201; i++) {
      try_count += 1;
      var realAddress = await getRealAddress(paly_address);
      console.log(realAddress);
      var downloadFileUrls = ["http://txmov2.a.yximgs.com", "http://v1-dy.ixigua.com", "http://v26-dy-cold.ixigua.com", "http://v26-dy.ixigua.com", "http://v26.douyinvod.com", "http://v27-dy-cold.ixigua.com", "http://v27-dy.ixigua.com", "http://v27.douyinvod.com", "http://v29-dy-cold.ixigua.com", "http://v29.douyinvod.com", "http://v3-b.douyinvod.com", "http://v3-c.douyinvod.com", "http://v3-d.douyinvod.com", "http://v3-dy-a.ixigua.com", "http://v3-dy-b.ixigua.com", "http://v3-dy-c.ixigua.com", "http://v3-dy-cold.ixigua.com", "http://v3-dy-d.ixigua.com", "http://v3-dy-x.ixigua.com", "http://v3-dy-y.ixigua.com", "http://v3-dy-z.ixigua.com", "http://v3-dy.ixigua.com", "http://v5-d.bdns.douyinvod.com", "http://v5-dy-a.ixigua.com", "http://v5-dy-b.ixigua.com", "http://v5-dy-c.ixigua.com", "http://v5-dy-e.ixigua.com", "http://v5-dy-f.ixigua.com", "http://v5-dy-g.ixigua.com", "http://v5-dy-h.ixigua.com", "http://v5-dy-i.ixigua.com", "http://v5-dy-j.ixigua.com", "http://v5-dy.ixigua.com", "http://v5-e.douyinvod.com", "http://v6-dy-cold.ixigua.com", "http://v6-dy-x.ixigua.com", "http://v6-dy-y.ixigua.com", "http://v6-dy-z.ixigua.com", "http://v6-dy.ixigua.com", "http://v6-x.douyinvod.com", "http://v6-y.douyinvod.com", "http://v6-z.douyinvod.com", "http://v9-dy-cold.ixigua.com", "http://v9-dy-x.ixigua.com", "http://v9-dy-y.ixigua.com", "http://v9-dy-z.ixigua.com", "http://v9-dy.ixigua.com", "http://v9.douyinvod.com", "http://v92-dy.ixigua.com", "http://v92.douyinvod.com", "http://v95-dy-a.ixigua.com", "http://v95-dy.ixigua.com", "http://v11.douyinvod.com", "http://v5-gdgz-c.douyinvod.com", "http://v26-x.douyinvod.com", "http://v5-gdgz.douyinvod.com", "http://v5-sjht-a.douyinvod.com", "http://v5-g.douyinvod.com", "http://v83-x.douyinvod.com", "http://v5-gdgz-a.douyinvod.com", "http://v3-y.douyinvod.com", "http://v1-x.douyinvod.com", "http://v96.douyinvod.com", "http://v3-d.douyinvod.com", "http://v5-i.douyinvod.com", "http://v9-z.douyinvod.com"];
      for (var j = 0; j < downloadFileUrls.length; j++) {
        if (realAddress.search(downloadFileUrls[j]) !== -1) {
          tested = true;
          break
        }
      }
      if (tested == true) break;
    }
    return {
      'code': 1,
      'tryCount': try_count,
      'tested': tested,
      'playAddress': realAddress,
      'cover': cover
    }
  }
}


async function getRealAddress(url) {
  const res = await requestNotRedirect(url);
  var pattern = new RegExp('href=\"(.*?)\"');
  if (pattern.test(res.body)) {
    return RegExp.$1;
  }

}


async function main(url) {
  var params = await getParam(url);
  if (params) {
    var res_json = await getItemInfo(params.item_id, params.mid)
    var result = await parse(res_json);
    return result
  } else {
    return {
      'code': 0
    }
  }
}

exports.main = async (event, context) => {
  return main(event.url)
}